﻿<script setup>
import { reactive, ref } from 'vue';
import { ElMessage } from 'element-plus';
import { useAuthStore } from '../stores/auth';
import { createCourseCategory } from '../api/demo';

const authStore = useAuthStore();

const formRef = ref();
const loading = ref(false);

const form = reactive({
  title: '',
  description: '',
});

const rules = {
  title: [{ required: true, message: '请输入课程类别名称', trigger: 'blur' }],
};

const handleSubmit = () => {
  if (!formRef.value) return;
  formRef.value.validate(async (valid) => {
    if (!valid) return;
    try {
      loading.value = true;
      await createCourseCategory({
        title: form.title,
        description: form.description,
        userid: authStore.user?.id,
      });
      ElMessage.success('课程类别添加成功');
      form.title = '';
      form.description = '';
      formRef.value?.clearValidate();
    } catch (error) {
      ElMessage.error(error?.message || '添加类别失败，请稍后重试');
    } finally {
      loading.value = false;
    }
  });
};

const handleReset = () => {
  form.title = '';
  form.description = '';
  formRef.value?.clearValidate();
};
</script>

<template>
  <div class="page-container">
    <el-card shadow="hover">
      <template #header>
        <div class="card-header">
          <div>
            <h2>新增课程类别</h2>
            <p>用于在首页中分类展示课程，系统会自动设置类别类型为“课程”。</p>
          </div>
        </div>
      </template>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px" size="large">
        <el-form-item label="类别名称" prop="title">
          <el-input v-model="form.title" maxlength="20" show-word-limit placeholder="请输入类别名称" />
        </el-form-item>
        <el-form-item label="备注说明">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="3"
            placeholder="可填写类别介绍或备注信息"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :loading="loading" @click="handleSubmit">提交保存</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<style scoped>
.page-container {
  max-width: 720px;
  margin: 0 auto;
}

.card-header h2 {
  font-size: 24px;
  margin-bottom: 4px;
}

.card-header p {
  color: #666;
}
</style>
